import dayjs from "dayjs";
import mongoose from "mongoose";

const Schema = mongoose.Schema;

const AuthorSchema = new Schema({
  first_name: {
    type: String,
    required: true,
    max: 100,
  },
  family_name: {
    type: String,
    required: true,
    max: 100,
  },
  date_of_birth: {
    type: Date,
  },
  date_of_death: {
    type: Date,
  },
});

// 虚拟属性 name：表示作者全民
AuthorSchema.virtual("name").get(function () {
  return this.family_name + ", " + this.first_name;
});

// 虚拟属性 lifespan： 寿命
AuthorSchema.virtual("lifespan").get(function () {
  if (!this.date_of_birth) return "-";
  if (!this.date_of_death)
    return this.date_of_birth.getFullYear().toString() + "- 至今";
  return (
    this.date_of_death.getFullYear() - this.date_of_birth.getFullYear()
  ).toString();
});

// 虚拟属性 url: 作者URL
AuthorSchema.virtual("url").get(function () {
  return "/catalog/author/" + this._id;
});

AuthorSchema.virtual("birth_date_formatted").get(function () {
  return this.date_of_birth
    ? dayjs(this.date_of_birth).format("YYYY-MM-DD")
    : "";
});

AuthorSchema.virtual("death_date_formatted").get(function () {
  return this.date_of_death
    ? dayjs(this.date_of_death).format("YYYY-MM-DD")
    : "";
});

// 到处 Author 模型
export default mongoose.model("Author", AuthorSchema);
